package cn.datawin.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
@Service
public class TimerPool {

	private static TimerPool clientPool = null;

	private ScheduledExecutorService service = null;
	
	@Resource
	TimerService timerService;

	private TimerPool() {
		service = Executors.newScheduledThreadPool(3);
		/**
		 * 这里开启轮询
		 */
		checkpoll();
	}

	public static TimerPool createHttpClientPool() {
		if (clientPool == null) {
			return clientPool = new TimerPool();
		}
		return clientPool;
	}
	
	public void checkpoll() {
		service.scheduleAtFixedRate(new Runnable() {
			@Override
			public void run() {
				try {
					runtimer();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
		}, 30*1000, 30*60*1000, TimeUnit.MILLISECONDS);// 30秒后执行, 每隔半小时后轮询
	}
	
	public void runtimer() throws ParseException{
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		
		List<DBObject> list=timerService.findList("timer", new BasicDBObject("state", "0"));
		for (int i = 0; i < list.size(); i++) {
			DBObject dbObject2=list.get(i);
			Integer times=(Integer) dbObject2.get("datelong");
			
			if(null==dbObject2.get("exctime")){
				DBObject dbObject3=(DBObject) dbObject2.get("tasks");
				for(String set:dbObject3.keySet()){
					timerService.updateSingle("task",new BasicDBObject("_id",new ObjectId(set)),new BasicDBObject("state", "0").append("crawlerdate", sdf.format(new Date())));
				}
			}else{
				 Date lastd=sdf.parse(dbObject2.get("exctime").toString());
				 Calendar c = Calendar.getInstance();
			     c.add(Calendar.DAY_OF_MONTH, -times);
				 Date tod=sdf.parse(sdf.format(c.getTime()));
				 if(lastd.before(tod)){
					 DBObject dbObject3=(DBObject) dbObject2.get("tasks");
					 for(String set:dbObject3.keySet()){
						timerService.updateSingle("task",new BasicDBObject("_id",new ObjectId(set)),new BasicDBObject("state", "0").append("crawlerdate", sdf.format(new Date())));
					 }
				 }
			}
			timerService.updateSingle("timer", new BasicDBObject("_id",new ObjectId(dbObject2.get("_id").toString())), new BasicDBObject("exctime", sdf.format(new Date())));
		}
	}
}
